<template>
  <el-cascader
    size="small"
    :options="options"
    v-model="selectedOptions"
    v-bind="$attrs"
  ></el-cascader>
</template>

<script>
import {
  provinceAndCityData,
  regionData,
  // provinceAndCityDataPlus,
  // regionDataPlus,
  CodeToText
} from "element-china-area-data";
export default {
  name: "area-selector",
  components: {},
  props: {
    type: {
      type: String,
      default: "regionData"
    },
    value: {
      type: Object,
      default: () => ({})
    },
    valueFormat: {
      type: String,
      default: "code" // code  text  all
    }
  },
  data() {
    return {
      selectedOptions: [this.value.province, this.value.city, this.value.region]
    };
  },
  watch: {
    value(val) {
      const { province, city, region } = val;
      this.selectedOptions = [province, city, region];
    },
    selectedOptions: {
      handler(val) {
        this.value.province = val[0];
        this.value.city = val[1];
        this.value.region = val[2];
        this.value.addressInfo = this.code2Text(val).join("");
      }
    }
  },
  computed: {
    options() {
      switch (this.type) {
        case "provinceData":
          return provinceAndCityData.map(i => ({
            label: i.label,
            value: i.value
          }));
        case "provinceAndCityData":
          return provinceAndCityData;
        default:
          return regionData;
      }
    }
  },
  methods: {
    // handleChange(val) {
    //   let text = [];
    //   if (val.length > 0) {
    //     text = this.code2Text(val);
    //   }
    //   this.value.province = val[0];
    //   this.value.city = val[1];
    //   this.value.region = val[2];
    //   let obj = {
    //     province: val[0],
    //     city: val[0],
    //     region: val[1]
    //   };
    //   this.$emit("input", { ...this.value, ...obj });
    //   this.$emit("change", text);
    // },
    code2Text(val) {
      if (Array.isArray(val) && val.length > 0) {
        return val.map(i => this.code2Text(i));
      }
      return CodeToText[val];
    }
  }
};
</script>
